<?php 
namespace Admin\Model;
use Think\Model;

/**
* @author denny <denny@mobnt.com>
* @商品分类
* 
*/
class CategoryModel extends Model
{
	//调用create可以接收的字段
	protected $insertFields = array('cat_name','parent_id');
	protected $updateFields = array('id','cat_name','parent_id');
	//验证表单
	protected $_validate = array(
		array('cat_name','require','分类名不能为空',1,'regex',3),
		array('cat_name','1,30','分类名称的值最长不能超过30个字符！',1,'length',3),
		array('parent_id','number', '上级分类的ID，0：代表顶级必须是一个整数！', 2, 'regex', 3),
	);
	
    //分类递归方法
    public function getTree()
    {
    	$data = $this->select();
    	return $this->_resort($data);
    }
    
    private function _reSort(array $data,$parent_id=0,$level=0,$isClear=TRUE)
    {
    	static $ret = array();
    	if ($isClear)
    	    $ret = array();
    	foreach ($data as $k => $v){
    		if ($v['parent_id'] == $parent_id){
    			$v['level'] = $level;
    			$ret[] = $v;
    			$this->_reSort($data,$v['id'],$level+1,FALSE);
    		}	
    	}
    	return $ret;
    }

    public function getChildren(int $id)
    {
    	$data = $this->select();
    	return $this->_children($data,$id);
    }

    private function _children(array $data,$parent_id=0,$isClear=TRUE)
    {
    	static $ret = array();
		if($isClear)
			$ret = array();
		foreach ($data as $k => $v)
		{
			if($v['parent_id'] == $parent_id)
			{
				$ret[] = $v['id'];
				$this->_children($data, $v['id'], FALSE);
			}
		}
		return $ret;
    }
	
	//删除前
	public function _before_delete()
	{
		//找出全部分类
		$children = $this->getChildren($option['where']['id']);
		if ($children)
		{
			$children = implode(',',$children);
			$this->execute('DELETE FROM shop_category WHERE id IN($children)');
		}
	}
}